package com.dragon.graduation.menu.controller;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dragon.bean.BeanCopy;
import com.dragon.config.exception.exception.GlobalException;
import com.dragon.graduation.menu.controller.dto.MenuAddDTO;
import com.dragon.graduation.menu.controller.dto.MenuSearchDTO;
import com.dragon.graduation.menu.controller.dto.MenuUpdateDTO;
import com.dragon.graduation.menu.controller.vo.MenuParentVO;
import com.dragon.graduation.menu.controller.vo.MenuVO;
import com.dragon.graduation.menu.entity.MenuEntity;
import com.dragon.graduation.menu.service.MenuService;
import com.dragon.graduation.roleMenu.service.RoleMenuService;
import com.dragon.graduation.user.controller.vo.UserVO;
import com.dragon.graduation.userRole.entity.UserRoleEntity;
import com.dragon.graduation.userRole.service.UserRoleService;
import com.dragon.jwt.JwtUtil;
import com.dragon.results.page.ResultPage;
import com.dragon.results.result.HttpResult;
import com.dragon.util.MyPage;
import com.dragon.util.WrapperUtil;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 菜单表 前端控制器
 * </p>
 *
 * @author dragon
 * @since 2025-02-28 21:18:53
 */
@RestController
@RequestMapping("/menu")
@RequiredArgsConstructor
@Api(tags = "菜单表 相关接口")
public class MenuController {

    private final MenuService menuService;
    private final RoleMenuService roleMenuService;
    private final UserRoleService userRoleService;

    @PostMapping("add")
    @ApiOperation("1]菜单表添加")
    @ApiOperationSupport(order = 1)
    public HttpResult<String> add(@RequestBody MenuAddDTO addDTO) {
        MenuEntity entity = MenuAddDTO.to(addDTO, MenuEntity.class);
        menuService.save(entity);
        return HttpResult.ok("添加成功");
    }

    @PostMapping("update")
    @ApiOperation("2]菜单表修改")
    @ApiOperationSupport(order = 2)
    public HttpResult<String> update(@RequestBody MenuUpdateDTO updateDTO) {
        MenuEntity entity = menuService.getById(updateDTO.getId());
        Assert.isFalse(ObjectUtils.isEmpty(entity), () -> new GlobalException("要修改的数据不存在"));
        entity = MenuUpdateDTO.to(updateDTO, MenuEntity.class);
        menuService.updateById(entity);
        return HttpResult.ok("修改成功");
    }

    @PostMapping("search")
    @ApiOperation("3]菜单表分页查询")
    @ApiOperationSupport(order = 3)
    public HttpResult<ResultPage<List<MenuVO>>> search(@RequestBody MenuSearchDTO searchDTO) {
        QueryWrapper<MenuEntity> queryWrapper = WrapperUtil.constructWrapper(searchDTO, MenuEntity.class);

        Page<MenuEntity> entityPage = MyPage.setPage(MenuEntity.class, searchDTO.getPage());
        Page<MenuEntity> page = menuService.page(entityPage, queryWrapper);
        ResultPage<List<MenuVO>> resultPage = MyPage.copyPage(page, MenuVO.class);
        return HttpResult.okForData(resultPage);
    }

    @PostMapping("delete")
    @ApiOperation("4]菜单表删除")
    @ApiOperationSupport(order = 4)
    public HttpResult<String> delete(@RequestBody List<Integer> idList) {
        menuService.removeByIds(idList);
        return HttpResult.ok("删除成功");
    }

    @GetMapping("tree")
    @ApiOperation("5]获取当前用户菜单树")
    @ApiOperationSupport(order = 5)
    public HttpResult<List<Tree<Integer>>> menuTree(){
        String token = JwtUtil.getTokenFromRequest();
        UserVO userVO = JwtUtil.parseToken(token, UserVO.class);
        UserRoleEntity userRole=userRoleService.getRoleById(userVO.getId());
        List<Tree<Integer>> tree= new ArrayList<>();
        if (ObjectUtils.isNotEmpty(userRole)) {
            List<MenuEntity> list=roleMenuService.getMenuByRole(userRole.getRoleId());
            tree= buildTree(list);
        }

        return HttpResult.okForData(tree);
    }
    @GetMapping("tree/all")
    @ApiOperation("6]获取所有菜单树")
    @ApiOperationSupport(order = 6)
    public HttpResult<List<Tree<Integer>>> tree() {
        List<MenuEntity> entityList = menuService.list();
        List<Tree<Integer>> tree = buildTree(entityList);
        if (CollectionUtils.isEmpty(tree)) {
            tree = new ArrayList<>();
        }
        return HttpResult.okForData(tree);
    }

    @GetMapping("parent")
    @ApiOperation("7]获取父节点")
    @ApiOperationSupport(order = 7)
    public HttpResult<List<MenuParentVO>> parent(){
        List<MenuEntity> list = menuService.lambdaQuery().eq(MenuEntity::getParentId, 0).list();
        List<MenuParentVO> result = BeanCopy.copyList(list, MenuParentVO.class);
        return HttpResult.okForData(result);
    }

    @GetMapping("find/role")
    @ApiOperation("8]根据角色id查询")
    @ApiOperationSupport(order = 8)
    @ApiImplicitParam(name = "roleId", value = "角色id",dataTypeClass = Integer.class)
    public HttpResult<List<Integer>> findByRole(Integer roleId){
         List<Integer> idList =roleMenuService.getMenuIdByRole(roleId);
         return HttpResult.okForData(idList);
    }


    public List<Tree<Integer>> buildTree(List<MenuEntity> data) {
        //1.配置
        TreeNodeConfig config = new TreeNodeConfig();
        //默认id，可以不设置
        config.setIdKey("id");
        //父id
        config.setParentIdKey("parentId");
        //分类名称
        config.setNameKey("name");
        //最大递归深度
        config.setDeep(5);
        //孩子节点
        config.setChildrenKey("children");
        config.setWeightKey("sort");

        //2.转树
        return TreeUtil.build(data, 0, config, ((object, treeNode) -> {
            treeNode.putExtra("id", object.getId());
            treeNode.putExtra("parentId", object.getParentId());
            treeNode.putExtra("name", object.getName());
            treeNode.putExtra("icon", object.getIcon());
            treeNode.putExtra("type", object.getType());
            treeNode.putExtra("status", object.getStatus());
            treeNode.putExtra("sort", object.getSort());
            treeNode.putExtra("component", object.getComponent());
            treeNode.putExtra("router", object.getRouter());
            //扩展属性...
        }));
    }
}
